package com.runa.monitor.platinterface.mqtt;

import com.runa.monitor.comm.StormAIData.DownstreamMessage;
import com.runa.monitor.comm.dto.newComm.AsynResult;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

import java.util.ArrayList;
import java.util.Arrays;


/**
 * mqtt服务端
 */
@Slf4j
public class MQTTConnector {


    private MqttAsyncClientPool pool;


    public MQTTConnector(String clientId, MQTTExecutor mqttExecutor) {
        pool = new MqttAsyncClientPool(clientId, mqttExecutor);
    }

    public MQTTConnector(String clientId) {
        pool = new MqttAsyncClientPool(clientId, null);
    }

    /**
     * 消息发布
     */
    public void sendMessage(String topic, String json) {
        sendMessage(topic, json.getBytes());
    }

    public void sendMessage(String topic, byte[] bytes) {
        MQTTAsyncClient client = pool.nextPublisher();
        if (null != client) {
            client.sendBytes(topic, bytes);
        } else {
            log.error("sendMessage bytes MQTT客户端不存在: {}", topic);
        }
    }


    public void sendMessageForService(AsynResult asynResult) {
        sendMessage("comm/down", asynResult);
    }

    /**
     * 上报
     * @param topic
     * @param asynResult
     */
    public void sendMessage(String topic, AsynResult asynResult) {
        MQTTAsyncClient client = pool.nextPublisher();
        if (null != client) {
            client.sendAsyncResult(topic, asynResult);
//            log.info("count: {}", count.incrementAndGet());
        } else {
            log.error("sendMessage AsynResult MQTT客户端不存在: {}", topic);
        }
    }

    public void sendMessage(String topic, DownstreamMessage message) {
        MQTTAsyncClient client = pool.nextPublisher();
        if (null != client) {
            client.sendMessage(topic, message);
        } else {
            log.error("sendMessage DownstreamMessage MQTT客户端不存在: {}", topic);
        }
    }


    public void sendMessage(String topic, MqttMessage message) {
        MQTTAsyncClient client = pool.nextPublisher();
        if (null != client) {
            client.sendMessage(topic, message);
        } else {
            log.error("sendMessage MqttMessage MQTT客户端不存在: {}", topic);
        }
    }
}
